package com.intramirror.product.controller;

import com.intramirror.core.common.exception.ValidateException;
import com.intramirror.core.common.response.ErrorResponse;
import com.intramirror.core.common.response.Response;
import com.intramirror.product.entity.LimitTime;
import com.intramirror.product.entity.TagProductRel;
import com.intramirror.product.service.ILimitTimeService;
import com.intramirror.product.service.IProductService;
import com.intramirror.product.vo.LimitTimeTagPrdRelVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created on 2018/1/21.
 * @author Admin
 */
@RestController
public class LimitTimeController {

    private final static Logger LOGGER = LoggerFactory.getLogger(LimitTimeController.class);
    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    IProductService productService;

    @Autowired
    ILimitTimeService limitTimeService;

    @GetMapping(value = "/limitTime/info")
    public Response getLimitTimeInfo() {
        LOGGER.info("LimitTimeController.getLimitTimeTags");
        return Response.status(1).data(limitTimeService.getLimitTimeInfo());
    }

    @GetMapping(value = "/limitTime/product/count")
    public Response getLimitTimeItemPrdCount(@RequestParam(value = "tagIds") String tagIds) {
        LOGGER.info("LimitTimeController.getLimitTimeItemPrdCount");

        if (tagIds == null) {
            throw new ValidateException(new ErrorResponse("The tagIds could not be null!"));
        }

        List<String> listTagId = Arrays.asList(tagIds.split(","));
        if (listTagId == null || listTagId.size() <= 0) {
            throw new ValidateException(new ErrorResponse("Failed to format tagIds!"));
        }

        return Response.status(1).data(productService.countProductByTagIds(listTagId));
    }

    @GetMapping(value = "/limitTime/product/{tagId}")
    public Response getProductByTagId(@PathVariable(value = "tagId") Long tagId) {
        LOGGER.info("LimitTimeController.getProductByTagId");

        if (tagId == null) {
            throw new ValidateException(new ErrorResponse("The tagId could not be null!"));
        }

        List<Map<String, Object>> listLimitTimeProduc = productService.getProductByTagId(tagId);
        if (listLimitTimeProduc == null || listLimitTimeProduc.size() <= 0) {
            return Response.status(1).data(null);
        }

        for (int i = 0; i < listLimitTimeProduc.size(); i++) {

            Map<String, Object> map = listLimitTimeProduc.get(i);
            Long productId = Long.parseLong(map.get("productId").toString());
            Double boutiqueDiscount = Double.parseDouble(map.get("boutiqueDiscount").toString());
            Double retailPrice = Double.parseDouble(map.get("retailPrice").toString());

            //去Redis取限时折扣的IM discount，计算出限时折扣的IM价格
            Double limitTimeIMDiscount = getLimitTimeIMDiscount(productId, boutiqueDiscount);
            BigDecimal limitTimeIMPrice = BigDecimal.valueOf(retailPrice).multiply(new BigDecimal(limitTimeIMDiscount)).setScale(2, BigDecimal.ROUND_HALF_UP);

            map.put("limitTimeIMPrice", limitTimeIMPrice);
            map.put("limitTimeIMDiscount", limitTimeIMDiscount);
        }

        return Response.status(1).data(listLimitTimeProduc);
    }

    private Double getLimitTimeIMDiscount(Long productId, Double boutiqueDiscount) {
        //还没实现
        return 0.0;
    }

    @PostMapping(value = "/limitTime/save")
    @Transactional
    public Response saveLimitTimeProducts(@RequestBody LimitTimeTagPrdRelVO limitTimeTagPrdRelVO) {
        Boolean result = true;

        Long tagId = limitTimeTagPrdRelVO.getTagId();
        List<TagProductRel> listTagPrdRel = limitTimeTagPrdRelVO.getListTagPrdRel();

        if (tagId != null && listTagPrdRel != null) {
            LOGGER.info("listTagPrdRel: [" + listTagPrdRel.toString() + "]");
            //更新tag_product_rel关系
            if (!limitTimeService.saveLimitTimeProducts(listTagPrdRel, tagId)) {
                result = false;
            }
        }

        limitTimeService.saveLimitItemDescription(tagId, limitTimeTagPrdRelVO.getItemDescription());

        LimitTime lt = limitTimeTagPrdRelVO.getLimitTime();
        if (lt != null) {
            LOGGER.info("lt: [" + lt.toString() + "]");

            //更新配置
            if (!limitTimeService.saveLimitTime(lt)) {
                result = false;
            }
        }

        return Response.status(1).data(result);
    }

    @GetMapping(value = "/limitTime/tags/{tagType}")
    public Response getLimitTimeTags(@PathVariable(value = "tagType") Long tagType) {
        return Response.status(1).data(productService.selectByType(tagType));
    }
}
